package com.hsurosy.domain.activity.service.quota.rule.impl;

import com.hsurosy.domain.activity.model.entity.ActivityCountEntity;
import com.hsurosy.domain.activity.model.entity.ActivityEntity;
import com.hsurosy.domain.activity.model.entity.ActivitySkuEntity;
import com.hsurosy.domain.activity.model.valobj.ActivityStateVO;
import com.hsurosy.domain.activity.service.quota.rule.AbstractActionChain;
import com.hsurosy.types.enums.ResponseCode;
import com.hsurosy.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author Hsu琛君珩
 * @Date 2024-11-08 18:35
 * @Description 活动规则过滤节点【日期、状态】
 * @Version: v1.0.0
 */
@Slf4j
@Component("activity_base_action")
public class ActivityBaseActionChain extends AbstractActionChain {

    /**
     * 校验活动的基本信息（状态、日期、库存）。
     *
     * @param activitySkuEntity 活动 SKU 实体
     * @param activityEntity 活动实体
     * @param activityCountEntity 活动次数实体
     * @return 校验成功返回 true
     * @throws AppException 当活动状态、日期或库存不符合要求时，抛出异常
     */
    @Override
    public boolean action(ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity) {
        log.info("活动责任链-基础信息【有效期、状态、库存(sku)】校验开始。sku: {} activityId: {}", activitySkuEntity.getSku(), activityEntity.getActivityId());

        // 校验：活动状态是否为开放
        if (!ActivityStateVO.open.equals(activityEntity.getState())) {
            throw new AppException(ResponseCode.ACTIVITY_STATE_ERROR.getCode(), ResponseCode.ACTIVITY_STATE_ERROR.getInfo());
        }

        // 校验：活动日期是否在有效期内「开始时间 <- 当前时间 -> 结束时间」
        Date currentDate = new Date();
        if (activityEntity.getBeginDateTime().after(currentDate) || activityEntity.getEndDateTime().before(currentDate)) {
            throw new AppException(ResponseCode.ACTIVITY_DATE_ERROR.getCode(), ResponseCode.ACTIVITY_DATE_ERROR.getInfo());
        }

        // 校验：活动sku的剩余库存「剩余库存从缓存中获取」
        if (activitySkuEntity.getStockCountSurplus() <= 0) {
            throw new AppException(ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(), ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());
        }

        // 调用下一个责任链节点进行后续校验
        return next().action(activitySkuEntity, activityEntity, activityCountEntity);
    }

}
